<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2019/4/23
 * Time: 0:12
 */

namespace App\Controller\admin\admin;

use App\Controller\Base;
use App\Lib\Redis;
use App\Model\AuAdmin;
use App\Model\AuAdminRole;
use App\Model\AuRole;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class Admin
 * @package App\Controller\admin\admin
 * @Controller(prefix="a/admin")
 * @Middleware(\App\Middleware\AdminMiddleware::class)
 */
class AdminController extends Base {
    /**
     * 管理员列表
     * @return array
     * @throws \Exception
     * @RequestMapping(path="lists",methods="get")
     */
    public function getLists() {
        $status = $this->get('status');
        $condition = [];
        if ($status == 'no') {
            $condition['status'] = 0;
        } elseif ($status == 'yes') {
            $condition['status'] = 1;
        }
        $lists = AuAdmin::query()
            ->where($condition)
            ->select('id', 'account', 'name', 'status')
            ->get()->toArray();
        // 查询角色
        $roles = AuAdminRole::query()
            ->join('au_role as r', 'role_id', '=', 'r.id')
            ->where('status', 1)
            ->select('user_id', 'name')
            ->get()->toArray();
        foreach ($lists as &$list) {
            $list['roles'] = '';
            foreach ($roles as $role) {
                if ($list['id'] == $role['user_id']) {
                    $list['roles'] = $list['roles'] . $role['name'] . ',';
                }
            }
            $list['roles'] = trim($list['roles'], ',');
        }
        return success(['lists' => $lists]);
    }

    /**
     * 添加/编辑用户信息
     * @return array
     * @RequestMapping(path="save",methods="post")
     */
    public function postSave() {
        $param = [
            'username' => $this->body('username'),
            'passwd' => $this->body('passwd'),
            'name' => $this->body('name'),
            'passwdCheck' => $this->body('passwdCheck'),
            'id' => $this->body('id'),
        ];
        if (empty($param['username']) || empty($param['name'])) {
            return error('参数错误');
        }
        $data = [
            'account' => $param['username'],
            'name' => $param['name'],
        ];
        if ($param['id']) {
            if ($param['passwd']) {
                if ($param['passwd'] !== $param['passwdCheck']) {
                    return error('两次输入密码不相同');
                } else {
                    $data['password'] = saltMd5($param['passwd']);
                }
            }
            $r = AuAdmin::query()
                ->where('id', $param['id'])
                ->update($data);
        } else {
            if ($param['passwd'] !== $param['passwdCheck']) {
                return error('两次输入密码不相同');
            } else {
                $data['password'] = saltMd5($param['passwd']);
            }
            $r = AuAdmin::query()->insert($data);
        }
        return $r !== false ? success() : error();
    }

    /**
     * 更改状态
     * @return array
     * @throws \Exception
     * @RequestMapping(path="status",methods="post")
     */
    public function postStatus() {
        $status = $this->body('status');
        $id = $this->body('id');
        if ($id == 1) {
            return error('此账号不能禁用');
        }
        if ($status) {
            $data = ['status' => 1];
        } else {
            $data = ['status' => 0];
        }
        $r = AuAdmin::query()
            ->where('id', $id)
            ->update($data);
        return $r ? success() : error();
    }

    /**
     * 获取角色
     * @return array
     * @RequestMapping(path="role",methods="get")
     */
    public function getRole() {
        $id = $this->get('id');
        $lists = AuRole::query()
            ->where('status', 1)
            ->select('id as value', 'name as label')
            ->get()->toArray();
        // 判断是否拥有权限
        $roles = AuAdminRole::query()
            ->where('user_id', $id)
            ->pluck('role_id')->toArray();
        return success(['lists' => $lists, 'has' => $roles]);
    }

    /**
     * 更新角色
     * @return array
     * @RequestMapping(path="role",methods="post")
     */
    public function postRole() {
        $param = [
            'id' => $this->body('id'),
            'roles' => $this->body('roles'),
        ];
        if (empty($param['id'])) {
            return error('非法参数');
        }
        AuAdminRole::query()->where('user_id', $param['id'])->delete();
        if ($param['roles']) {
            $param['roles'] = explode(',',$param['roles']);
            $data = [];
            foreach ($param['roles'] as $role) {
                $data[] = [
                    'user_id' => $param['id'],
                    'role_id' => $role,
                ];
            }
            AuAdminRole::query()->insert($data);
        }
        Redis::get()->hSet("token:a", "{$param['id']}", 0);
        return success();
    }
}
